import * as React from 'react';
import { getStorageSync, request, View } from "remax/wechat";
import {
    ImageUpload,
    Button,
    Cell,
    Col,
    Form,
    Card,
    Row, Tag, Popup, Loading
} from "annar";
import { usePageEvent } from "remax/macro";
import { origin } from "@/config/config";
import { VideoCategory } from "@/type/category";

import 'weui-miniprogram/miniprogram_dist/weui-wxss/dist/style/weui.wxss';
import { wxLogin } from "@/pages/index";
import { useState } from "react";

export default () => {
    const [show, setShow] = React.useState(false);
    const [msg, setMsg] = React.useState('');
    const [isUploadImg, setIsUploadImg] = React.useState('yellow')
    const [isUploadV, setIsUploadV] = React.useState('yellow')
    const [form] = Form.useForm()
    const [value, setValue] = React.useState<string[]>([]);
    const [categories, setCategories] = React.useState<string[]>([])
    const [cover, setCover] = React.useState('')
    const [video, setVideo] = React.useState('')
    const [loading, setLoading] = React.useState(false)


    usePageEvent('onLoad', () => {
        wx.request({
            url: `${origin}/category/getAllCategoryList`,
            success: (res: any) => {
                if (res.data.code === 200 && res.data.data !== []) {
                    let categoryList: VideoCategory[] = res.data.data
                    let categories1: string[] = []
                    categoryList.forEach((item, index) => {
                        categories1[index] = item.name
                        setCategories(categories1)
                    })
                }
            }
        })
    })


    const handleFinishFailed = (values: any, errorFields: any) => {
        console.log('errorFields', errorFields);
    };

    const handleSubmit = () => {
        form.submit()
        let loginInfo;
        console.log(isUploadV)
        if (isUploadV === 'yellow') {
            setMsg("视频还没有上传")
            setShow(true)
        } else {
            // 上传数据到服务器
            try {
                loginInfo = getStorageSync('loginInfo')
            } catch (e) {
                wxLogin() // 登录
            }

            console.log("fas")
            console.log(categories)
            console.log(form.getFieldsValue())
            console.log(loginInfo.token)
            wx.request({
                url: `${origin}/video/add/`,
                header: {
                    'token': loginInfo.token,
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'Accept': 'application/json',
                },
                method: "POST",
                data: {
                    name: form.getFieldValue('name'),
                    category: categories[form.getFieldValue('category')],
                    cover: cover,
                    video: video
                },
                success: (res: any) => {
                    console.log(res.data)
                    if (res.data.code === 200) {
                        wx.redirectTo({ url: '/pages/success/index' })
                    } else {
                        setMsg(res.msg)
                        setShow(true)
                    }
                }
            })
           
            
        }
    };


    const handleChange = (file: any[]) => {
        console.log(file)
        setMsg("正在上传")
        setLoading(true)
        setShow(true)
        wx.uploadFile({
            url: 'https://api.liangchao.top/upload/cover',
            filePath: file[0],
            name: 'file',
            // formData: {
            //     'user': 'test'
            // },
            success: (res) => {
                const data = res.data
                let maps = data.replace(new RegExp("\{", "g"), '')
                    .replace(new RegExp("\}", "g"), "")
                    .replace(new RegExp("\"", "g"), "").trim()
                    .replace(/\s+/g, "")
                    .replace(new RegExp("\n", "g"), "")
                    .split(",")
                for (let i = 0; i < maps.length; i++) {
                    if (maps[i].split(":")[0] === "data") {
                        setCover(maps[i].split(":")[1])

                    }
                }
                setLoading(false)
                setShow(false)
                setValue(file);
                setIsUploadImg('green')
                //do something
            }
        })


    };

    const handleFinish = (values: any) => {

    };

    return (
        <View>
            <Card contentStyle={{ padding: '20px 0 20px', margin: '0px', }}>
                <Form form={form} onFinish={handleFinish} onFinishFailed={handleFinishFailed}>
                    <Form.Item noStyle name="name" rules={[{ required: true }]}>
                        <Cell.Input label="视频描述" placeholder="描述你的视频" border={false} />
                    </Form.Item>

                    <Form.Item noStyle name="category" rules={[{ required: true }]}>
                        <Cell.Picker
                            label="分类"
                            placeholder="请选择分类"
                            range={categories}
                            border={false}
                        />
                    </Form.Item>

                    <Form.Item
                        label="封面"
                        name="cover"
                        valuePropName="files"
                        rules={[{ required: true }]}
                    >
                        <ImageUpload files={value} maxCount={1} deletable={false} onChange={handleChange} />
                    </Form.Item>

                    <Row gutter={8} style={{ padding: '0 20px' }}>
                        <Col span={10}>
                            <Button
                                size="large"
                                shape="square"
                                plain
                                hairline
                                color="blue"
                                block
                                onTap={() => {
                                    if (isUploadV !== 'green') {
                                        wx.chooseMedia({
                                            count: 1,
                                            mediaType: ['video'],
                                            sourceType: ['album', 'camera'],
                                            camera: 'back',
                                            success(res) {
                                                console.log(res.tempFiles[0].tempFilePath)
                                                console.log(isUploadV)
                                                console.log(isUploadV === 'green')
                                                setMsg("正在上传")
                                                setLoading(true)
                                                setShow(true)
                                                
                                                wx.uploadFile({
                                                    url: 'https://api.liangchao.top/upload/video',
                                                    filePath: res.tempFiles[0].tempFilePath,
                                                    name: 'file',
                                                    // formData: {
                                                    //     'user': 'test'
                                                    // },
                                                    success: (res) => {
                                                        const data: string = res.data
                                                        let maps = data.replace(new RegExp("\{", "g"), '')
                                                            .replace(new RegExp("\}", "g"), "")
                                                            .replace(new RegExp("\"", "g"), "").trim()
                                                            .replace(/\s+/g, "")
                                                            .replace(new RegExp("\n", "g"), "")
                                                            .split(",")
                                                        for (let i = 0; i < maps.length; i++) {
                                                            if (maps[i].split(":")[0] === "data") {
                                                                console.log(maps[i].split(":")[1])
                                                                setVideo(maps[i].split(":")[1])
                                                                console.log("aa", video)
                                                                setLoading(false)
                                                                setShow(false)
                                                            }
                                                        }

                                                        setIsUploadV('green')
                                                    }
                                                })

                                            }
                                        })
                                    } else {
                                        setShow(true)
                                        setMsg('已经上传过视频了')
                                    }
                                }}
                            >
                                上传视频
                            </Button>
                            <Row>
                                <Tag color={isUploadV}
                                    style={{ marginTop: "10px" }}>{isUploadV == 'green' ? '已上传视频' : '未上传视频'}</Tag>
                                <Tag color={isUploadImg}
                                    style={{ marginTop: "10px" }}>{isUploadImg == 'green' ? '已上传图片' : '未上传图片'}</Tag>
                            </Row>


                        </Col>
                        <Col span={10}>
                            <Button size="large" shape="square" look="orange" block onTap={handleSubmit}>
                                提交
                            </Button>
                        </Col>
                    </Row>
                </Form>
            </Card>
            <Popup
                open={show}
                onClose={() => {
                    setShow(false);
                }}
            >
                <View
                    style={{
                        padding: '80px',
                    }}
                >
                    {msg}
                    {loading && <Loading />}
                </View>
            </Popup>
        </View>
    )
}